package com.ruicar.afs.cloud.afscase.approvemakelabel.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.approvemakelabel.entity.ApproveMakeLabel;
import com.ruicar.afs.cloud.afscase.approvemakelabel.service.ApproveMakeLabelService;
import com.ruicar.afs.cloud.afscase.approvetask.entity.CaseApproveRecord;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.manuallabel.condition.ManualLabelCondition;
import com.ruicar.afs.cloud.afscase.manuallabel.entity.ManualLabel;
import com.ruicar.afs.cloud.afscase.manuallabel.service.ManualLabelService;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.UseSceneEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author jiaqi.guo
 * @version 1.0
 * @description: 手动打标签
 * @created 2020/5/19 11:38
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("信审标签信息保存")
@RequestMapping("/makeLabel")

public class ApproveMakeLabelController {

    private ApproveMakeLabelService approveMakeLabelService;
    private ManualLabelService manualLabelService;
    private CaseBaseInfoService caseBaseInfoService;
    private CaseApproveRecordService caseApproveRecordService;

    @PostMapping(value = "/addApproveLabel/{params}")
    @ApiOperation(value = "新增信审标签信息")
    @Transactional
    @SysLog("新增信审标签信息")
    public IResponse<Boolean> addApproveLabel(@PathVariable String params) {
        String[] str = params.split(",");
        String applyNo = str[0];
        //根据申请编号查询List 保留整体对象查询
        List<ApproveMakeLabel> oldLabelList = approveMakeLabelService.queryLabelByApplyNo(applyNo);
        List<String> idsList = new ArrayList<>();
        List<String> labelId = new ArrayList<>();
        if (oldLabelList != null & oldLabelList.size() > 0) {
            for (int i = 0; i < oldLabelList.size(); i++) {
                idsList.add(oldLabelList.get(i).getId().toString());
                labelId.add(oldLabelList.get(i).getLabelId().toString());
            }
        }
        //根据ID批量删除
        if (idsList != null && idsList.size() > 0) {
            approveMakeLabelService.removeByIds(idsList);

        }
        //保存新增
        List<ApproveMakeLabel> labelList = new ArrayList();
        String strIds = "";
        String updateLabel="";
        List<String> listStr= new ArrayList<>();
        CaseApproveRecord record = new CaseApproveRecord();
        for (int i = 1; i < str.length; i++) {
            strIds += str[i] + ",";
            listStr.add(str[i]);
            ApproveMakeLabel approveMakeLabel = new ApproveMakeLabel();
            ManualLabel manualLabel = manualLabelService.queryAllLabelListById(Long.parseLong(str[i]));
            approveMakeLabel.setApplyNo(applyNo);
            approveMakeLabel.setLabelId(manualLabel.getId());
            approveMakeLabel.setLabelName(manualLabel.getLabelName());
            approveMakeLabel.setLabelPhase(manualLabel.getLabelPhase());
            approveMakeLabel.setLabelColor(manualLabel.getLabelColor());
            approveMakeLabel.setLabelType(manualLabel.getLabelType());
            approveMakeLabel.setLabelLocation(manualLabel.getLabelLocation());
            approveMakeLabel.setLabelSort(manualLabel.getLabelSort());
            approveMakeLabel.setLabelPattern(manualLabel.getLabel());
            approveMakeLabel.setLabelClassification(manualLabel.getLabelClassification());
            approveMakeLabel.setCreateBy(SecurityUtils.getUsername());
            approveMakeLabel.setIsArchive(manualLabel.getIsArchive());
            labelList.add(approveMakeLabel);
          if(CollectionUtils.isEmpty(labelId)){
              updateLabel+=manualLabel.getLabelName()+",";
              record.setApproveSuggestName("新增标签");
          }
        }
        approveMakeLabelService.saveBatch(labelList);
        /**案件基础信息*/
        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                .eq(CaseBaseInfo::getApplyNo, applyNo));
        if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
            String labelIdRepeat = caseBaseInfo.getLabelIdRepeat();
            labelIdRepeat += strIds + ",";
            caseBaseInfo.setLabelIdRepeat(labelIdRepeat);
            caseBaseInfoService.updateById(caseBaseInfo);
        }
        /**保存新增标签操作日子*/
        if(CollectionUtils.isNotEmpty(listStr)&&CollectionUtils.isNotEmpty(labelId)){
            List<String> intersection=null;
            if(listStr.size()>labelId.size()){
                 intersection = listStr.stream().filter(item -> !labelId.contains(item)).collect(toList());
                 record.setApproveSuggestName("新增标签");
            }
            if(listStr.size()<labelId.size()){
                 intersection = labelId.stream().filter(item -> !listStr.contains(item)).collect(toList());
                 record.setApproveSuggestName("删除标签");
            }
            if(listStr.size()==labelId.size()){
                record.setApproveSuggestName("进行标签操作");
            }
            if(CollectionUtils.isNotEmpty(intersection)){
                for(int t=0;t<intersection.size();t++){
                    ManualLabel manualLabel = manualLabelService.queryAllLabelListById(Long.parseLong(intersection.get(t)));
                    updateLabel+=manualLabel.getLabelName()+",";
                }
            }
        }
        if(CollectionUtils.isEmpty(listStr)&&CollectionUtils.isNotEmpty(labelId)){
            for(int t=0;t<labelId.size();t++){
                ManualLabel manualLabel = manualLabelService.queryAllLabelListById(Long.parseLong(labelId.get(t)));
                updateLabel+=manualLabel.getLabelName()+",";
            }
            record.setApproveSuggestName("删除标签");
        }
        record.setUseScene(UseSceneEnum.APPROVE.getValue());
        record.setDisposeStaff(SecurityUtils.getUser()==null?"system":SecurityUtils.getUser().getUserRealName());
        record.setApproveStartTime(new Date());
        record.setApproveEndTime(new Date());
        record.setApplyNo(applyNo);
        record.setDisposeNodeName("手动打标签");
        record.setApproveRemark(updateLabel);
        caseApproveRecordService.save(record);
        return new IResponse<Boolean>().setMsg("新增标签库成功");
    }

    @PostMapping(value = "/queryAllLabelList")
    @ApiOperation(value = "查詢所有信息数据")
    public IResponse<IPage<ManualLabel>> queryAllLabelList(@PathVariable ManualLabelCondition manualLabel) {
        return IResponse.success(manualLabelService.page(new Page(manualLabel.getPageNumber(), manualLabel.getPageSize()), Wrappers.<ManualLabel>query().lambda()
                .like(StringUtils.isNotEmpty(manualLabel.getLabelName()), ManualLabel::getLabelName, manualLabel.getLabelName())
        ));
    }

    @PostMapping(value = "/queryAllLabelByApplyNo/{applyNo}")
    @ApiOperation(value = "根据申请编号差数据")
    public IResponse<List<ApproveMakeLabel>> queryAllLabelByApplyNo(@PathVariable String applyNo) {

        return IResponse.success(approveMakeLabelService.queryLabelByApplyNo(applyNo));
    }

    @PostMapping(value = "/queryAllLabelById/{id}")
    @ApiOperation(value = "根据申请编号差数据")
    public IResponse<ApproveMakeLabel> queryAllLabelById(@PathVariable String id) {

        return IResponse.success(approveMakeLabelService.getById(id));
    }

}